﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Log.Controller;
using System.Reflection;
using System.Threading;

namespace Util
{
    public class CallingThread
    {
        static FormLibrary.Loading form = null;
        public static void CreateThread(string _namespaces, string _class, string _method)
        {
            try
            {
                CreateThread(_namespaces + "." + _class, _method);
            }
            catch (Exception ex)
            {
                LogController.WriteLog(System.Runtime.InteropServices.Marshal.GetExceptionCode(), ex, Funcs.GetIpClient());
            }
        }

        public static void CreateThread(string _class, string _method)
        {
            try
            {
                string[] strList = new string[] { _class, _method };
                Thread thread = new Thread(new ParameterizedThreadStart(CreateInvoke));
                thread.IsBackground = true;
                thread.Start(strList);

                form = new FormLibrary.Loading();
                form.ShowDialog();
            }
            catch (Exception ex)
            {
                LogController.WriteLog(System.Runtime.InteropServices.Marshal.GetExceptionCode(), ex, Funcs.GetIpClient());
            }
        }

        private static void CreateInvoke(object obj)
        {
            try
            {
                string[] strList = (string[])obj;
                Type calledType = Type.GetType(strList[0]);

                calledType.InvokeMember(
                    strList[1],
                    BindingFlags.InvokeMethod | BindingFlags.Public |
                        BindingFlags.Static,
                    null,
                    null,
                    null);

                // Dispose form
                int iCount = 0;
                while (form == null && iCount < 5)
                {
                    Thread.Sleep(100);
                    iCount++;
                }
                if (form != null)
                {
                    form.DisposeForm();
                    form = null;
                }
            }
            catch (Exception ex)
            {
                LogController.WriteLog(System.Runtime.InteropServices.Marshal.GetExceptionCode(), ex, Funcs.GetIpClient());
            }
        }
    }
}
